package com.zgs.mall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zgs.common.utils.R;
import com.zgs.mall.order.constant.OrderConstant;
import com.zgs.mall.order.entity.OrderItemEntity;
import com.zgs.mall.order.enume.OrderStatusEnum;
import com.zgs.mall.order.feign.CartFeignService;
import com.zgs.mall.order.feign.MemberFrignService;

import com.zgs.mall.order.feign.WareFeignService;
import com.zgs.mall.order.interceptor.OrderUserLoginInterceptor;
import com.zgs.mall.order.to.OrderCreateTO;
import com.zgs.mall.order.to.SeckillOrderTo;
import com.zgs.mall.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgs.common.utils.PageUtils;
import com.zgs.common.utils.Query;

import com.zgs.mall.order.dao.OrderDao;
import com.zgs.mall.order.entity.OrderEntity;
import com.zgs.mall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    MemberFrignService memberFrignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    com.zgs.mall.order.feign.WareFeignService wareFeignService;
    @Autowired
    org.springframework.data.redis.core.StringRedisTemplate stringRedisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;

    ThreadLocal<SubmitVo> threadLocal =new ThreadLocal<SubmitVo>();


    /**
     * 创建秒杀单
     * @param orderTo
     */
    @Transactional
    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {
        //保存订单
        //保存订单项

    }
    @GlobalTransactional
    @Transactional
    @Override
    public void seataTesta() throws ExecutionException, InterruptedException {
        OrderEntity order =new OrderEntity();
        order.setOrderSn("55");
        order.setBillContent("554");
        this.save(order);


        CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
            memberFrignService.seataTest();
        }, threadPoolExecutor);

        CompletableFuture.allOf(voidCompletableFuture1).get();

    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }
    @Transactional
    @Override
    public void orderClose(OrderEntity entity) {
        Long id = entity.getId();
        OrderEntity orderEntity = this.getById(id);
        Integer status = orderEntity.getStatus();
        if (status ==0){
            OrderEntity orderEntity1 = new OrderEntity();
            orderEntity1.setId(id);
            orderEntity1.setStatus(4);
            this.updateById(orderEntity1);
            //发送Mq消息进行扣减库存
            try{
                // 每一个
                rabbitTemplate.convertAndSend("order-event-exchange","stock.release.#",orderEntity);
            }catch(Exception e){
                //将没发出去的
            }

        }
    }



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void test() {

    }

    /**
     * 订单确认页返回的数据
     * @return
     */
    @Override
    public OrdeerConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        //获取当前线程的请求上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        OrdeerConfirmVo vo =new OrdeerConfirmVo();
        MemberRespVo memberRespVo = OrderUserLoginInterceptor.userInfo.get();
        Long id = memberRespVo.getId();

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程获取用户地址
            List<MemberAddressVo> address = memberFrignService.getAddress(id);
            vo.setAddressVos(address);
        }, threadPoolExecutor);


        CompletableFuture<Void> userCartItemsFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程获取用户地址
            //所有选中的购物项--价格要获取最新的
            List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
            vo.setItemVos(userCartItems);
        }, threadPoolExecutor).thenRunAsync(()->{
            List<OrderItemVo> itemVos = vo.getItemVos();
            //查询库存
            List<Long> collect = itemVos.stream().map(orderItemVo -> {
                return orderItemVo.getSkuId();
            }).collect(Collectors.toList());
            R skuhasStock = wareFeignService.getSkuhasStock(collect);
            List<SkuHasStockVo> data = skuhasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            Map<Long, Boolean> collect1 = data.stream().collect(Collectors.toMap(stock -> stock.getSkuId(), stock -> stock.getHasStock()));
        },threadPoolExecutor);

        //feign 在远程调用之前要构造请求，要调用很多拦截器
        //RequestInterceptor
        //积分--优惠券信息
        Integer integration = memberRespVo.getIntegration();
        vo.setIntegration(integration);
        //TODO 防重令牌
        String uuid= UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+id,uuid,30, TimeUnit.MINUTES);
        vo.setOrderToken(uuid);
        CompletableFuture.allOf(addressFuture,userCartItemsFuture).get();
        return vo;
    }

    /**
     * 下单创建订单
     * @param submitVo
     * @return
     */
    @Transactional
    @Override
    public SubmitOrderResponse submitOrder(SubmitVo submitVo) {
        SubmitOrderResponse response =new SubmitOrderResponse();
        MemberRespVo vo = OrderUserLoginInterceptor.userInfo.get();
        Long id = vo.getId();
        String orderToken = submitVo.getOrderToken();
        String script="if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        //原子验证和原子删除
        Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX+id), orderToken);
        if (lock1==0){//请不要重复提交
            response.setCode(1);
            return response;
        }
        threadLocal.set(submitVo);
        //创建订单项
        OrderCreateTO order = createOrder();
        //验价（失败->提示商品价格发生变化，请重新确认->重定向订单确认页->结束）
        BigDecimal payAmount = order.getOrderEntity().getPayAmount();
        BigDecimal payPrice = submitVo.getPayPrice();
        int abs = Math.abs(payAmount.subtract(payPrice).intValue());
        if (abs>0.01){//失败->提示商品价格发生变化，请重新确认
            response.setCode(2);
            return response;
        }
        //保存订单所有信息到数据库、
        OrderEntity orderEntity = order.getOrderEntity();
        save(orderEntity);

        //远程锁库存
        WareSkuLockVo wareSkuLockVo =new WareSkuLockVo();
        wareSkuLockVo.setOrderSn(orderEntity.getOrderSn());
        List<OrderItemEntity> orderItemEntities = order.getOrderItemEntities();
        List<OrderItemVo> collect = orderItemEntities.stream().map(item -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setCount(item.getSkuQuantity());
            orderItemVo.setSkuId(item.getSkuId());
            return orderItemVo;
        }).collect(Collectors.toList());
        wareSkuLockVo.setLocks(collect);
        R r = wareFeignService.orderLockStock(wareSkuLockVo);
        if (r.getCode()!=0){
            response.setCode(3);
            response.setOrder(order.getOrderEntity());
            return response;
        }
        response.setOrder(order.getOrderEntity());
        response.setCode(0);
        return response;
        //订单号，订单项，sku名字 ，数量
    }


    //创建订单
    private OrderCreateTO createOrder(){
        OrderCreateTO to =new OrderCreateTO();
        //创建订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        //从购物车获取订单项--当前用户的购物项 创建订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
            to.setOrderItemEntities(orderItemEntities);
        //计算订单金额信息
        computePrice(orderEntity,orderItemEntities);
        to.setOrderEntity(orderEntity);
        return to;
    }
    //计算订单金额信息
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal totalPrice=new BigDecimal("0");
        for (OrderItemEntity itemEntity : orderItemEntities) {
            BigDecimal skuPrice = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity()));
            totalPrice=totalPrice.add(skuPrice);
        }
        orderEntity.setTotalAmount(totalPrice);
        orderEntity.setPayAmount(totalPrice);
        //订单优惠总额计算
    }

    private OrderEntity buildOrder(String orderSn){
        OrderEntity entity = new  OrderEntity();
        entity.setOrderSn(orderSn);
        //订单状态
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //TODO获取收货地址信息，填充订单
        //远程去库存那边拿地址
        return entity;
    }
    /**
     * 创建订单项
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后一次确定每个购物车的价格
        List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
        if(userCartItems !=null){
            List<OrderItemEntity> collect = userCartItems.stream().map(item -> {
                OrderItemEntity itemEntity = buildOrderItem(item) ;
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
    /**
     * 创建每一个订单项
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setSkuId(item.getSkuId());
        itemEntity.setSkuName(item.getTitle());
        itemEntity.setSkuPrice(item.getPrice());
        itemEntity.setSkuPic(item.getImage());
        //商品sku属性
        List<String> skuAttr = item.getSkuAttr();
        String s = StringUtils.collectionToDelimitedString(skuAttr, ";");
        itemEntity.setSkuAttrsVals(s);
        itemEntity.setSkuQuantity(item.getCount());
        return itemEntity;
    }

}